//
//  EvaluateViewController.m
//  B2C
//
//  Created by 李小龙 on 2017/8/2.
//  Copyright © 2017年 lixiaolong. All rights reserved.
//

#import "EvaluateViewController.h"
#import "EvaluateTableViewCell.h"

#import "HeartFiveView.h"
#import "LXLImageButton.h"
#import "LXLChooseImageModel.h"
#import "LXLMultiPhotoTableViewController.h"

#import "RAYUploader.h"

@interface EvaluateViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,UITableViewDataSource,UITableViewDelegate,RAYUploaderDelegate>
{
    ALAssetsLibrary * _assetsLibrary;
//    CGFloat _buttonX;
//    CGFloat _buttonS; // 间距
//    CGFloat _buttonW;
}
//@property (weak, nonatomic) IBOutlet UIView *backView;
//@property (weak, nonatomic) IBOutlet SZTextView *textView;
//@property (weak, nonatomic) IBOutlet UIView *showPictureView;
//@property (weak, nonatomic) IBOutlet UIButton *anonymityButton;
//@property (weak, nonatomic) IBOutlet NSLayoutConstraint *contentBackHLayout;
//
//@property (strong, nonatomic) HeartFiveView *heartView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

//@property (nonatomic, strong) EvaluateTableViewCell *clickCell;
@property (nonatomic, strong) EvaluateModel *clickModel;

//@property (nonatomic, strong) UIButton *addImageButton;
@property (nonatomic, strong) UIImagePickerController *imagePickerController;
//@property (nonatomic, strong) NSMutableArray *selectImageArr;
@property (nonatomic, assign) NSInteger maxSelectImageCount;
@property (nonatomic, strong) NSMutableArray *assetsGroups;

@property (nonatomic, assign) NSInteger totalImageCount;
@property (nonatomic, assign) NSInteger uploadImageCount;
@end

@implementation EvaluateViewController
#pragma mark - Get
//- (HeartFiveView *)heartView {
//    if (!_heartView) {
//        _heartView = [[HeartFiveView alloc] init];
//        _heartView.canEdit = YES;
//        [_backView addSubview:_heartView];
//    }
//    return _heartView;
//}
- (UIImagePickerController *)imagePickerController {
    if (!_imagePickerController) {
        //初始化图片选择器
        _imagePickerController = [[UIImagePickerController alloc]init];
        _imagePickerController.delegate = self;
        _imagePickerController.allowsEditing = YES;
    }
    return _imagePickerController;
}
- (NSMutableArray *)assetsGroups {
    if (!_assetsGroups) {
        _assetsGroups = [[NSMutableArray alloc] init];
    }
    return _assetsGroups;
}
//- (NSMutableArray *)selectImageArr {
//    if (!_selectImageArr) {
//        _selectImageArr = [[NSMutableArray alloc] init];
//    }
//    return _selectImageArr;
//}
- (NSMutableArray<EvaluateModel *> *)tableArray {
    if (!_tableArray) {
        _tableArray = [[NSMutableArray alloc] init];
    }
    return _tableArray;
}
//#pragma mark - IBAction
//- (IBAction)anonymityButtonAction:(id)sender {
//    UIButton *button = (UIButton *)sender;
//    [button setSelected:!button.selected];
//}

#pragma mark - ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"订单评价";
    UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithTitle:@"发布" style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonAction:)];
    NSDictionary *dic = [NSDictionary dictionaryWithObject:[UIColor colorWithHex:0x030303 alpha:1.0] forKey:NSForegroundColorAttributeName];
    [right setTitleTextAttributes:dic forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = right;
    
    self.maxSelectImageCount = 9;
    _assetsLibrary = [[ALAssetsLibrary alloc] init];
    [self.tableView clearExtendCellLine];
    
}
- (void)viewDidAppear:(BOOL)animated {
    
    LXLChooseImageModel *chooseModel = [LXLChooseImageModel shareInstance];
    if (chooseModel.chooseImageArr.count > 0) {
        for (int i = 0; i < chooseModel.chooseImageArr.count; i++) {
            ALAsset *asset = (ALAsset *)chooseModel.chooseImageArr[i];
            //            UIImage *image = [UIImage imageWithCGImage:[[asset defaultRepresentation] fullResolutionImage]];
            UIImage *image = [UIImage imageWithCGImage:asset.aspectRatioThumbnail];
            [self updateBottomView:image];
        }
        [chooseModel.chooseImageArr removeAllObjects];
        
    }
    [self.tableView reloadData];
    [super viewDidAppear:animated];
}
#pragma mark - action
- (void)rightBarButtonAction:(id)sender {
    NSLog(@"发布");
    [self.view endEditing:YES];
    
    _totalImageCount = 0;
    _uploadImageCount = 0;
    
    for (NSInteger i = 0; i < self.tableArray.count; i++) {
        EvaluateModel *tempModel = self.tableArray[i];
//        if (tempModel.escore.intValue <= 0) {
//            [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"请给商品打分" animated:YES];
//            return;
//        }
//        if (!TextIsNotNil(tempModel.econtent)) {
//            [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"请输入您的评价内容" animated:YES];
//            return;
//        }
//        if (tempModel.imgArray.count == 0) {
//            [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"请添加评价图片" animated:YES];
//            return;
//        }
        _totalImageCount += tempModel.imgArray.count;
    }
    
    // 发布的接口，有图片先上传图片（用七牛？）上传参数：几颗心、内容、图片url、是否匿名
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    for (NSInteger i = 0; i < self.tableArray.count; i++) {
        EvaluateModel *tempModel = self.tableArray[i];
        dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            for (NSInteger j = 0; j < tempModel.imgArray.count; j++) {
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    RAYUploader *uploader = [RAYUploader defaultUploader];
                    uploader.delegate = self;
                    struct RAYUploaderIndex index = {i, j};
//                    if ([[tempModel.imgArray objectAtIndex:j] isKindOfClass:[UIImage class]]) {
//                        [uploader uploadWithFile:[tempModel.imgArray objectAtIndex:j] type:0 index:index];
//                    }
                    [uploader uploadWithFile:[tempModel.imgArray objectAtIndex:j] type:0 index:index];
                });
            }
        });
    }
    
    if (_totalImageCount == 0) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [self uploadEvaluate];
    }
    
}
#pragma mark - RAYUploaderDelegate
- (void)uploadWithQNResponseInfo:(QNResponseInfo *)info fileUrl:(NSURL *)url resp:(NSDictionary *)resp type:(NSInteger)type index:(RAYUploaderIndex)index {
    dispatch_async(dispatch_get_main_queue(), ^{
        NSString *imageUrl = [NSString stringWithFormat:@"%@%@",URL_QiNiu_Prefix,[resp objectForKey:@"hash"]];
        NSLog(@"url - %@",imageUrl);
        if (type == 0) {
            _uploadImageCount++;
            [self.tableArray[index.i].imgArray replaceObjectAtIndex:index.j withObject:imageUrl];
            if (_uploadImageCount == _totalImageCount) {
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                [self uploadEvaluate];
            }
        }
    });
    
}
- (void)uploadError:(NSError *)error {
    if (error) {
        NSLog(@"uploader Image Error - %@",error);
    }
    [MBProgressHUD hideHUDForView:self.view animated:YES];
}

#pragma mark - 网络请求
- (NSMutableDictionary *)getUploaderDic {
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    NSString *gids = @"", *osids = @"", *escores = @"", *econtents = @"", *eiimgs = @"", *isanonymouss = @"";
    for (NSInteger i = 0; i < self.tableArray.count; i++) {
        EvaluateModel *tempModel = self.tableArray[i];
        if (i == 0) {
            gids = tempModel.gid;
            osids = tempModel.osid;
            escores = tempModel.escore;
            econtents = tempModel.econtent;
            isanonymouss = [NSString stringWithFormat:@"%d",tempModel.isanonymous];
            for (NSInteger j = 0; j < tempModel.imgArray.count; j++) {
                NSString *tempImgUrl = tempModel.imgArray[j];
                if (j == 0) {
                    eiimgs = tempImgUrl;
                } else {
                    eiimgs = [NSString stringWithFormat:@"%@,%@",eiimgs,tempImgUrl];
                }
            }
        } else {
            gids = [NSString stringWithFormat:@"%@,%@",gids,tempModel.gid];
            osids = [NSString stringWithFormat:@"%@,%@",osids,tempModel.osid];
            escores = [NSString stringWithFormat:@"%@,%@",escores,tempModel.escore];
            econtents = [NSString stringWithFormat:@"%@,%@",econtents,tempModel.econtent];
            isanonymouss = [NSString stringWithFormat:@"%@,%@",isanonymouss,[NSString stringWithFormat:@"%d",tempModel.isanonymous]];
            
            NSString *tempeiimgs = @"";
            for (NSInteger j = 0; j < tempModel.imgArray.count; j++) {
                NSString *tempImgUrl = tempModel.imgArray[j];
                if (j == 0) {
                    tempeiimgs = tempImgUrl;
                } else {
                    tempeiimgs = [NSString stringWithFormat:@"%@,%@",tempeiimgs,tempImgUrl];
                }
            }
            eiimgs = [NSString stringWithFormat:@"%@|%@",eiimgs,tempeiimgs];
        }
    }
    [dic setObject:gids forKey:@"gids"];
    [dic setObject:osids forKey:@"osids"];
    [dic setObject:escores forKey:@"escores"];
    [dic setObject:econtents forKey:@"econtents"];
    [dic setObject:eiimgs forKey:@"eiimgs"];
    [dic setObject:isanonymouss forKey:@"isanonymouss"];
    return dic;
}
- (void)uploadEvaluate {
    
    // 从数组中循环取数据 商品用 | 分割， 图片用 , 分割
    NSMutableDictionary *dic = [self getUploaderDic];
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    //    [self startLoadingGifView];
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:URL_Save_All_Evaluate parameters:dic success:^(NSURLSessionDataTask *task, id responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSDictionary *dics = responseObject;
        
        if ([[dics objectForKey:@"code"] isEqualToString:@"200"]) {
            [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"提交成功" animated:YES];
            if (self.block) {
                self.block(YES);
            }
            [weakSelf disMissSelf];
        } else {
            
            [MBProgressHUD showError:weakSelf.view title:dics[@"message"] code:[dics objectForKey:@"code"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showError:weakSelf.view title:@"" code:@"" animated:YES];
    }];
}

#pragma mark - 打开相册
// 添加图片按钮点击事件
- (void)addImageButtonAction {
    UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [actionSheet addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        // 打开照相机
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"不支持摄像头,请查看摄像权限！" animated:YES];
            return;
        }
        
        self.imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:self.imagePickerController animated:YES completion:^{
            //
        }];
    }]];
    [actionSheet addAction:[UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //        // 打开系统相册
        //        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        //            [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"图片库不可用,请查看隐私权限！" animated:YES];
        //            return;
        //        }
        //        self.imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        //        [self presentViewController:self.imagePickerController animated:YES completion:^{
        //
        //        }];
        // 打开自定义多选相册
        [self openPhotoLibrary];
    }]];
    [actionSheet addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        // 取消
        
    }]];
    
    [self presentViewController:actionSheet animated:YES completion:nil];
}
- (void)updateBottomView:(UIImage *)image {
    if (self.clickModel.imgArray.count < 9) {
        [self.clickModel.imgArray addObject:image];
    }
}
- (void)openPhotoLibrary {
    // 自定义多选相册
    [self createPhotoGroup];
}
- (void)createPhotoGroup {
    [self.assetsGroups removeAllObjects];
    //枚举相册的Block
    void (^assetsGroupsEnumerationBlock)(ALAssetsGroup *,BOOL *) = ^(ALAssetsGroup *assetsGroup, BOOL *stop) {
        [assetsGroup setAssetsFilter:[ALAssetsFilter allAssets]];
        
        if (stop) {
            if (assetsGroup.numberOfAssets > 0) {
                [self.assetsGroups addObject:assetsGroup];
            }
        }
        
        if (assetsGroup == nil) {
            if (self.assetsGroups.count > 0) {
                // 模态系统相册列表
                LXLMultiPhotoTableViewController *groupVC = [[LXLMultiPhotoTableViewController alloc] init];
                //                BaseNavigationViewController *nav = [[BaseNavigationViewController alloc] initWithRootViewController:groupVC];
                [groupVC.allGroupsArr addObjectsFromArray:self.assetsGroups];
                groupVC.selectNum = self.clickModel.imgArray.count;
                groupVC.maxNum = _maxSelectImageCount;
                //NSLog(@"%@",self.assetsGroups);
                
                [self presentViewController:groupVC animated:YES completion:nil];
            }
        }
        
    };
    //查找相册失败block
    void(^assetsGroupsFailureBlock)(NSError *) = ^(NSError *error) {
        NSLog(@"Error: %@", [error localizedDescription]);
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请打开 设置-隐私-照片 允许访问您的图片库" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert show];
    };
    
    [_assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:assetsGroupsEnumerationBlock failureBlock:assetsGroupsFailureBlock];
}
#pragma mark - UIImagePickerControllerDelegate
// 拍照完成回调
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo NS_DEPRECATED_IOS(2_0, 3_0) {
    
    NSLog(@"finish..");
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        
        //图片存入相册
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
        // 更新UI
        [self updateBottomView:image];
        [self.tableView reloadData];
    } else if (picker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary) {
        NSLog(@"相册返回");
        
    }
    [self dismissViewControllerAnimated:YES completion:nil];
    
}
//进入拍摄页面点击取消按钮
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.tableArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 4;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    EvaluateModel *model = self.tableArray[indexPath.section];
    EvaluateTableViewCell *cell = [EvaluateTableViewCell evaluateCellWith:tableView indexPath:indexPath count:1];
    [cell updateCellWith:model indexPath:indexPath count:1];
    
    __block typeof(cell) blockCell = cell;
    HeartFiveView *heart = [cell heartViewWithIndexPath:indexPath];
    __block typeof(heart) blockHeart = heart;
    heart.block = ^(NSInteger tag) {
        [blockHeart setImageViewWithPoint:tag+1 withType:HeartTypeForNormal];
        model.escore = [NSString stringWithFormat:@"%ld",(long)tag+1];
    };
    cell.block = ^(EvaluateType type) {
        self.clickModel = model;
        switch (type) {
            case EvaluateTypeAddImage:
            {
                [self addImageButtonAction];
            } break;
            case EvaluateTypeAnonymity:
            {
                model.isanonymous = blockCell.thirdAnonymityButton.selected;
            } break;
            case EvaluateTypeHeart:
            {
                
            } break;
            case EvaluateTypeDeleteImage:
            {
                [self.tableView reloadData];
            } break;
            default:
                break;
        }
    };
    return cell;
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    EvaluateModel *model = self.tableArray[indexPath.section];
    switch (indexPath.row) {
        case 0:
            return 100;
        case 1: case 3:
            return 44;
        case 2:
        {
            CGFloat width = (ScreenWidth-30.0-15.0*2)/3.0;
            NSInteger count = 0;
            if (model.imgArray.count < 9) {
                count = model.imgArray.count/3;
            } else {
                count = 2;
            }
            return 127+width + count*(width+15);
        }
        default:
            return 0;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section < self.tableArray.count-1) {
        return 5;
    }
    return 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.width, 5)];
    [view setBackgroundColor:[UIColor clearColor]];
    return view;
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesEnded:touches withEvent:event];
    [self.view endEditing:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
